import ObjectPool from '@/ObjectPool';
import UIShopModel from '../Model/UIShopModel';
import { Frame } from '@/frame';
import PlayerUtil from '@/PlayerUtil';
import FrameTipUtil from '../common/FrameTipUtil';
import SyncUtil from '@/SyncUtil';
import InputUtil from '@/InputUtil';
import ColorStr from '@/ColorStr';

const shopSize = 98;

export default class UIShopView {
    model: UIShopModel;
    /** 每个格子到物品数据的映射，用于显示物品提示 */
    // gridMapItemData: Map<string, ShopItemModel> = new Map();
    gridMapItemData: { [key: string]: ShopItemModel } = {};
    private gridPool: ObjectPool<Frame[]> = new ObjectPool<Frame[]>(
        this.poolCreator
    );
    poolCreator() {
        let f = Frame.createGLUEBUTTON();
        f.setSize(0.025, 0.025).setParent(
            UIManager.UIShopInstance.rootFrame.current
        );
        let art = f.addBackgroundImage('');
        f.setOnMouseEnter(UIShopView.showTip);
        f.setOnMouseLeave(UIShopView.hideTop);
        f.setOnClick(UIShopView.shopGridClickHandler);
        let mask = Frame.createTEXT(f.current);
        mask.setSize(0.025, 0.025).setVisible(false).setPoint2Center(f.current);
        return [f, art, mask];
    }
    static shopGridClickHandler() {
        let h = DzGetTriggerUIEventFrame();
        let p = DzGetTriggerUIEventPlayer();
        let _this = UIManager.UIShopInstance;
        let d = _this.gridMapItemData['f' + h];
        if (d == null) return;
        // 非售卖部分需要判断金钱是否够
        if (_this.currentType != 'sold') {
            if (PlayerUtil.getGold(p) < d.goldcost) {
                FrameTipUtil.showFailText('金币不足');
                return;
            }
        }
        // 能否可以购买/出售
        if (_this.currentType == 'recipe') {
            FrameTipUtil.showFailText('你无法购买该买物品，请按照公式合成');
            return;
        }
        if (_this.currentType == 'skill' || _this.currentType == 'sold') {
            // 遮挡层
            UIShopView.masks.get(h).visible = true;
        }
        // ui动效
        if (_this.currentType == 'sold') {
            let x = InputUtil.getMouseSceneX(),
                y = InputUtil.getMouseSceneY();
            let ty = y + 0.025;
            FrameTipUtil.showIconText(
                'UI\\Feedback\\Resources\\ResourceGold.blp',
                `${ColorStr.gold} + ${R2I(d.goldcost / 2)}`,
                x,
                y,
                x,
                ty,
                0.7
            );
        } else {
            FrameTipUtil.showIconMoveIntoAnimation(
                d.Art,
                InputUtil.getMouseSceneX(),
                InputUtil.getMouseSceneY(),
                0.055,
                0.17,
                0.5,
                0.025,
                0.01
            );
        }
        SyncUtil.syncObjData('shop_buy_item', {
            id: d.id,
            index: d.index,
            type: _this.currentType,
            goldcost: d.goldcost,
        });
    }
    static hideTop() {
        UIManager.UIShopInstance.tipBackground.visible = false;
        UIManager.UIShopInstance.tipFrame.visible = false;
    }
    static showTip() {
        let handle = DzGetTriggerUIEventFrame();
        let p = DzGetTriggerUIEventPlayer();
        if (p == GetLocalPlayer()) {
            let _this = UIManager.UIShopInstance;
            let d = _this.gridMapItemData['f' + handle];
            if (d == null) return;
            _this.tipFrame.setText(_this.getItemTip(d));
            _this.tipFrame.visible = true;
            _this.tipBackground.visible = true;
        }
    }
    getItemTip(d: ShopItemModel): string {
        if (d == null) return '';
        let tip = `${d.Name}|n价格：${ColorStr.gold}${d.goldcost}|r|n${d.Description}`;
        if (d.recipe) {
            tip += `|r|n${d.recipe}`;
        }
        return tip;
    }
    constructor() {
        this.model = new UIShopModel();
        se.on('背包数据变化', this.refreshShopUI);

        // 当玩家选择英雄完毕之后画背包的ui
        se.on('created_hero', this.drawUI.bind(this));
    }
    drawUI() {
        this.draw();
        this.drawTip();
    }
    refreshShopUI(this: void, { db, p }) {
        if (p != GetLocalPlayer()) return;
        let _this = UIManager.UIShopInstance;
        _this.showShopList(_this.currentType, p);
    }
    drawTip() {
        this.tipBackground = new Frame(
            'BACKDROP',
            null,
            null,
            '_sl_border_backdrop',
            0
        );
        this.tipFrame = Frame.createTEXT();
        this.tipFrame
            .setPoint(
                FRAMEPOINT_TOPLEFT,
                this.rootFrame.current,
                FRAMEPOINT_TOPRIGHT,
                0.01,
                0
            )
            .setSize(0.13, 0)
            .setFont(0.01113, 'assets\\fonts\\fonts.ttf');
        this.tipBackground.setPoints(this.tipFrame.current, 0.007, 0.007);
        this.tipFrame.setVisible(false);
        this.tipBackground.setVisible(false);
    }
    // frames
    toggleButton: Frame;
    rootFrame: Frame;
    refreshBut: Frame;
    warningFrame: Frame;
    tipBackground: Frame;
    tipFrame: Frame;
    draw() {
        let f = Frame.createFrame();
        let bg = Frame.createBackDrop()
            .setSize(0.03, 0.03)
            .setAbsPoint(FRAMEPOINT_BOTTOMLEFT, 0.01, 0.165)
            .setTexture('assets\\shop.blp');
        this.toggleButton = Frame.createGLUETEXTBUTTON(f.current).setSize(
            0.03,
            0.03
        );
        this.toggleButton.setPoint2Center(bg.current);
        this.toggleButton.setOnClick(UIShopView.toggleClickHandler);
        // 根面板
        let root = (this.rootFrame = Frame.createFrame());
        root.setSize(0.29, 0.35).setAbsPoint(FRAMEPOINT_BOTTOMLEFT, 0.03, 0.2);
        // bg = Frame.createBackDrop(root.current).setSize(0.29, 0.35).setTexture('assets\\backpack\\black.blp');
        bg = new Frame(
            'BACKDROP',
            null,
            root.current,
            '_sl_border_backdrop',
            0
        );
        // bg.setPoint2Center(root.current);
        bg.setPoints(root.current, 0.008, 0.008);
        Frame.createTEXT(root.current)
            .setSize(0.03, 0.015)
            .setFont(0.01113, 'fonts\\fonts.ttf')
            .setText('商店')
            .setPoint(FRAMEPOINT_TOP, root.current, FRAMEPOINT_TOP, 0, 0)
            .setTextAlignment(TEXTALIGN_CENTER);
        // 分类按钮
        // let but1 = Frame.createGLUEBUTTON();
        // but1.setParent(root.current).setSize(0.04, 0.02).setPoint(FRAMEPOINT_TOPLEFT, root.current, FRAMEPOINT_TOPLEFT, 0.005, -0.02).addBackgroundImage('assets\\common\\but_base.blp');
        // but1.setOnClick(UIShopView.baseListShow);
        // let but2 = Frame.createGLUEBUTTON();
        // but2.setParent(root.current).setSize(0.04, 0.02).setPoint(FRAMEPOINT_TOPLEFT, root.current, FRAMEPOINT_TOPLEFT, 0.05, -0.02).addBackgroundImage('assets\\common\\but_com.blp');
        // but2.setOnClick(UIShopView.scrollShow);
        let but3 = Frame.createGLUEBUTTON();
        // but3.setParent(root.current).setSize(0.04, 0.02).setPoint(FRAMEPOINT_TOPLEFT, root.current, FRAMEPOINT_TOPLEFT, 0.095, -0.02).addBackgroundImage('assets\\common\\but_sk.blp');
        but3.setParent(root.current)
            .setSize(0.04, 0.02)
            .setPoint(
                FRAMEPOINT_TOPLEFT,
                root.current,
                FRAMEPOINT_TOPLEFT,
                0.005,
                -0.02
            )
            .addBackgroundImage('assets\\common\\but_sk.blp');
        but3.setOnClick(UIShopView.skillShopShow);

        let but4 = Frame.createGLUEBUTTON();
        // but4.setParent(root.current).setSize(0.04, 0.02).setPoint(FRAMEPOINT_TOPLEFT, root.current, FRAMEPOINT_TOPLEFT, 0.14, -0.02).addBackgroundImage('assets\\common\\but_sell.blp');
        but4.setParent(root.current)
            .setSize(0.04, 0.02)
            .setPoint(
                FRAMEPOINT_TOPLEFT,
                root.current,
                FRAMEPOINT_TOPLEFT,
                0.05,
                -0.02
            )
            .addBackgroundImage('assets\\common\\but_sell.blp');
        but4.setOnClick(UIShopView.soldButHandler);

        let but5 = (this.refreshBut = Frame.createGLUEBUTTON());
        but5.setParent(root.current)
            .setSize(0.04, 0.02)
            .setPoint(
                FRAMEPOINT_BOTTOMRIGHT,
                root.current,
                FRAMEPOINT_BOTTOMRIGHT,
                -0.01,
                0.02
            )
            .addBackgroundImage('assets\\common\\but_refresh.blp');
        but5.setOnClick(UIShopView.refreshButClickHandler);
        but5.visible = false;

        let but_c = Frame.createGLUEBUTTON();
        but_c
            .setParent(root.current)
            .setSize(0.015, 0.015)
            .setPoint(
                FRAMEPOINT_TOPRIGHT,
                root.current,
                FRAMEPOINT_TOPRIGHT,
                -0.005,
                -0.005
            )
            .addBackgroundImage('assets\\common\\but_close.blp');
        but_c.setOnClick(UIShopView.toggleClickHandler);

        let wt = (this.warningFrame = Frame.createTEXT());
        wt.setParent(root.current)
            .setSize(0.29, 0.015)
            .setTextColor(0xffff0000)
            .setFont(0.01113, 'assets\\fonts\\fonts.ttf')
            .setPoint(FRAMEPOINT_BOTTOM, root.current, FRAMEPOINT_BOTTOM);
        wt.setTextAlignment(TEXTALIGN_CENTER);
        wt.setText('');
        root.visible = false;
    }
    /** 刷新按钮点击 */
    static refreshButClickHandler() {
        let p = DzGetTriggerUIEventPlayer();
        let x = InputUtil.getMouseSceneX();
        let y = InputUtil.getMouseSceneY();
        let ty = y + 0.025;
        FrameTipUtil.showIconText(
            'UI\\Feedback\\Resources\\ResourceGold.blp',
            `${ColorStr.gold} - ${500}`,
            x,
            y,
            x,
            ty,
            0.7
        );
        SyncUtil.syncData('shop_refresh_click', I2S(GetPlayerId(p)));
    }
    /** 出售按钮点击 */
    static soldButHandler() {
        let p = DzGetTriggerUIEventPlayer();
        UIManager.UIShopInstance.showShopList('sold', p);
    }
    /** 技能商店点击 */
    static skillShopShow() {
        let p = DzGetTriggerUIEventPlayer();
        UIManager.UIShopInstance.showShopList('skill', p);
    }
    /** 卷轴分类点击 */
    static scrollShow() {
        let p = DzGetTriggerUIEventPlayer();
        UIManager.UIShopInstance.showShopList('recipe', p);
    }
    /** 基础分类点击 */
    static baseListShow() {
        let p = DzGetTriggerUIEventPlayer();
        UIManager.UIShopInstance.showShopList('base', p);
    }
    static toggleClickHandler() {
        let p = DzGetTriggerUIEventPlayer();
        let _this = UIManager.UIShopInstance;
        if (_this.rootFrame.visible) {
            _this.hide();
        } else {
            _this.show(p);
        }
    }
    show(p: player) {
        UIManager.UIShopInstance.rootFrame.visible = true;
        UIManager.UIShopInstance.showShopList(
            'skill',
            DzGetTriggerUIEventPlayer()
        );
    }
    hide() {
        UIManager.UIShopInstance.rootFrame.visible = false;
    }
    currentType: shopItemTypes = 'skill';
    static masks: Map<number, Frame> = new Map();
    /**  利用ui画出指定分类的商品*/
    showShopList(type: shopItemTypes, p: player) {
        if (p != GetLocalPlayer()) return;
        let _this = UIManager.UIShopInstance;
        _this.currentType = type;
        _this.gridPool.setAllIdleStatus(true);
        _this.refreshBut.visible = type == 'skill';
        _this.warningFrame.setText(
            type == 'recipe' ? '合成物品需要按照公式合成' : ''
        );
        let root = _this.rootFrame;
        let items: ShopItemModel[] = null;
        if (type == 'base' || type == 'recipe') {
            items = _this.model.getSoldList(type);
        } else if (type == 'skill') {
            items = _this.model.skillSoldListMap[GetPlayerId(p)].get('skill');
        } else if (type == 'sold') {
            items = _this.model.transBakpack2Shop(
                UIManager.UIBakpack.model.getBackPackData(p)
            );
        }
        // 清空旧的提示信息
        // 循环展示物品到ui
        for (let i = 0; i < shopSize; i++) {
            let [but, art, mask] = _this.gridPool.borrowObject();
            let x = 0.005 + 0.028 * (i % 10);
            let y = -0.028 * R2I(i / 10) - 0.055;
            let item = items[i];
            but.setPoint(
                FRAMEPOINT_TOPLEFT,
                root.current,
                FRAMEPOINT_TOPLEFT,
                x,
                y
            );
            if (item != null) {
                art.setTexture(item.Art);
                item.index = i;
                _this.gridMapItemData['f' + but.current] = item;
                mask.visible = false;
            } else {
                art.setTexture('assets\\bg_64x64.blp');
                mask.visible = true;
                _this.gridMapItemData['f' + but.current] = null;
            }
            UIShopView.masks.set(but.current, mask);
        }
        _this.gridPool.forDirtyObjects((f) => (f[0].visible = false));
    }
}
